package com.bicycletour.db;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.util.PropertiesUtils;

/**
 * 数据库连接类，通过该类可以获得数据库连接，可以在"database.properties"填写相关配置信息
 * 
 * @author 杨强
 */
public class C3P0Database {
    private static final C3P0Database instance = new C3P0Database();
    private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
    private static final Properties dbProperties = new Properties();

    static {
        try {
            dbProperties.load(ClassLoader
                    .getSystemResourceAsStream("database.properties"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        cpds.setUser(dbProperties.getProperty("database.user", "root"));
        cpds.setPassword(dbProperties.getProperty("database.password", "root"));
        cpds.setJdbcUrl(dbProperties.getProperty("database.url",
                "jdbc:mysql://127.0.0.1:3306/bicycletour"));

        try {
            cpds.setDriverClass(dbProperties.getProperty(
                    "database.driverClass", "com.mysql.jdbc.Driver"));
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        cpds.setInitialPoolSize(PropertiesUtils.getIntProperty(dbProperties,
                "database.initialPoolSize", 15));
        cpds.setMinPoolSize(PropertiesUtils.getIntProperty(dbProperties,
                "database.minPoolSize", 8));
        cpds.setMaxPoolSize(PropertiesUtils.getIntProperty(dbProperties,
                "database.maxPoolSize", 25));
        cpds.setMaxStatements(PropertiesUtils.getIntProperty(dbProperties,
                "database.maxStatements", 1000));
        cpds.setMaxIdleTime(PropertiesUtils.getIntProperty(dbProperties,
                "database.maxIdleTime", 60));
    }

    /**
     * 私有构造函数，创建单例模式
     */
    private C3P0Database() {

    }

    /**
     * 创建数据库实例对象
     * 
     * @return 数据库实例对象
     */
    public static final C3P0Database getInstance() {
        return instance;
    }

    /**
     * 获取数据库连接
     * 
     * @return 数据库连接
     */
    public static final Connection getConnection() {
        Connection conn = null;
        try {
            conn = C3P0Database.cpds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     * 
     * @param conn
     *            数据库连接
     */
    public static final void close(Connection conn) {
        try {
            if (null != conn) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
